package com.amway.qy.core.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amway.qy.core.constants.QyWechatUrls;
import com.amway.qy.util.common.QyHttpClientUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class DefaultAccessTokenImpl extends AbstractAccessTokenImpl {
	
	private static final Logger logger = LoggerFactory.getLogger(DefaultAccessTokenImpl.class);
	
	private final List<NameValuePair> paramsMap = new ArrayList<NameValuePair>();
	
	private String corpid;
	private String secrect;
	
	public DefaultAccessTokenImpl(String corpid,String secrect){
		this.corpid=corpid;
		this.secrect=secrect;
	}

	/*
	 * 每次提取access_token时，先判断本地缓存是否接近过期。
	 * 如果在过期前的15分钟，则依然使用现有的token，否则就重新从微信接口提取新的Token.
	 */
	@Override
	public boolean isExpired(){	
		return (tokenInfo.getCreateTime()+TimeUnit.SECONDS.toMillis(tokenInfo.getExpires_in())-System.currentTimeMillis() <= TimeUnit.MINUTES.toMillis(15)); 
	}
	
	@Override
	protected String getAccessTokenDirect() {
		String ret = null;		
		String result;		
		if(paramsMap.isEmpty()){
			paramsMap.add(new BasicNameValuePair("corpsecret", secrect));
			paramsMap.add(new BasicNameValuePair("corpid", corpid));
		}
		
		result = QyHttpClientUtils.httpsGet(QyWechatUrls.ACCESS_TOKEN_URL, paramsMap);
		
		logger.info("Recevied the AccessToken result :"+result);
		
		JsonObject jsonObject= new JsonParser().parse(result).getAsJsonObject();
		if(jsonObject.has("access_token")){
			long current = System.currentTimeMillis();
			tokenInfo.setCreateTime(current);
			tokenInfo.setAccess_token(jsonObject.get("access_token").getAsString());
			tokenInfo.setExpires_in(jsonObject.get("expires_in").getAsLong());
			tokenInfo.setLastAccessTime(current);
			ret = tokenInfo.getAccess_token();
		}else{
			throw new IllegalStateException(result);
		}		 
		return ret;
	}

	public String getCorpid() {
		return corpid;
	}

	public void setCorpid(String corpid) {
		this.corpid = corpid;
	}

	public String getSecrect() {
		return secrect;
	}

	public void setSecrect(String secrect) {
		this.secrect = secrect;
	}

	
}
